package cn.edu.pzhu.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import cn.edu.pzhu.pojo.Msg;
import cn.edu.pzhu.service.FileMsgService;
import cn.edu.pzhu.service.imp.FileMsgServiceImp;
import cn.pzhuweb.filesys.util.FileUtil;
import cn.pzhuweb.filesys.util.Result;

/**
 * Servlet implementation class DeleteFileServlet
 */
@WebServlet("/deletefile")
public class DeleteFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String filename = request.getParameter("filename");
		String username = request.getParameter("username");
		
//		System.out.println(filename);
//		System.out.println(username);
		
		HttpSession session = request.getSession();
		try {
			FileMsgService fms = new FileMsgServiceImp();
			String filepath = fms.findFilePath(filename,username);
//			System.out.println(filepath);
			Boolean res = FileUtil.deleteFile(filepath);
			Msg msg = fms.delete(filename);
		
			if(msg.isSuccess()) {
				System.out.println("数据库删除成功！");
			}else {
				System.out.println("数据库删除失败！");
			}
		
			if(res) {
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().print("<script>alert('删除成功!'); window.location.href='myshare.jsp';</script>");
			}else {
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().print("<script>alert('删除失败!'); window.location.href='myshare.jsp';</script>");
			}
		} catch (Exception e) {
			session.setAttribute("msg", "请先登录再使用此功能！");	
			session.setAttribute("msg1", "登录页面");
			session.setAttribute("url", "login.jsp");
			response.sendRedirect("error.jsp");
			return; //流程结束，后续代码不需要再执行...
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
